#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>

#include "sqlhelper.h"

SqlHelper::SqlHelper(QObject *parent) :
    QObject(parent)
{
}

bool SqlHelper::editTask(QSqlDatabase& db, CalendarItem& item, QWidget* parent)
{
    return true;
}

bool SqlHelper::deleteTask(QSqlDatabase& db, int id, bool confirm, QWidget* parent)
{
    if (confirm) {
        QMessageBox::StandardButton b = QMessageBox::information(parent, QString(), tr("Are you sure you want to delete this task?"), QMessageBox::Yes|QMessageBox::No);
        if (b != QMessageBox::Yes)
            return false;
    }

    QSqlQuery query = db.exec( QString("DELETE FROM ACTUAL WHERE id='%1'").arg(id) );
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return false;
    }

    return true;
}

bool SqlHelper::conflictTask(QSqlDatabase& db, int id, int userid, const QDateTime& start, const QDateTime& end)
{
    QString q = QString("select count(*) from ACTUAL where id!=%1 and userid=%2 and startTime<'%3' and endTime>'%4'").arg(id).arg(userid).arg(end.toString(Qt::ISODate)).arg(start.toString(Qt::ISODate));
    QSqlQuery query = db.exec(q);
    if (query.lastError().isValid()) {
        qDebug() << query.lastError().text();
        return false;
    }

    query.next();
    return query.value(0).toInt() > 0;
}
